package com.liveHere.www.dao;

import com.liveHere.www.Exception.UserDaoException;
import com.liveHere.www.po.User;
import com.liveHere.www.util.JDBCUtils;

import java.sql.*;

import java.util.ArrayList;

/**
 * @author Mo312
 */
public class UserDaoImpl implements UserDao {

    //实现注册
    @Override
    public boolean register(User user) throws Exception {
        String sql = "insert into users (username, password, phone, balance) values(?,?,?,?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getPhoneNumber());
            pstmt.setDouble(4, user.getBalance());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new UserDaoException("注册失败: " + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    //实现登录
    @Override
    public User login(String username, String password) throws Exception {
        String sql = "select * from users where username=? and password=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setUserid(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhoneNumber(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setBalanceStatus(rs.getString("balance_status"));
                user.setAmountToBeRecharged(rs.getDouble("amount_to_be_recharged"));

                return user;
            }
        } catch (SQLException e) {
            throw new UserDaoException("登录失败: " + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
        return null;
    }

    //更新账户余额
    @Override
    public boolean updateBalance(int userId, double amount) throws Exception {
        String sql = "UPDATE users SET balance = balance + ? WHERE user_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, amount);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new UserDaoException("更新账户余额失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    //更新个人信息
    @Override
    public boolean updateUserInfo(User user) throws Exception {
        String sql = "update users set username=?,password=?,phone=? where user_id=?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getPhoneNumber());
            pstmt.setInt(4, user.getUserid());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new UserDaoException("更新个人信息失败: " + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }

    }

    // 查询待审核的用户充值
    @Override
    public ArrayList<User> getPendingRecharges() throws Exception {
        String sql = "SELECT * FROM users WHERE amount_to_be_recharged > 0 AND balance_status = 'pending'";
        ArrayList<User> users = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setUserid(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhoneNumber(rs.getString("phone"));
                user.setBalance(rs.getDouble("balance"));
                user.setBalanceStatus(rs.getString("balance_status"));
                user.setAmountToBeRecharged(rs.getDouble("amount_to_be_recharged"));
                users.add(user);
            }
        } catch (SQLException e) {
            throw new UserDaoException("查询待审核的用户充值失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
        return users;
    }

    // 审核通过用户充值
    @Override
    public void approveRecharge(int userId) throws Exception {
        String sql = "UPDATE users SET balance_status = 'approved' WHERE user_id = ? and balance_status = 'pending'";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new UserDaoException("审核通过用户充值失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }

    }

    // 审核拒绝用户充值
    @Override
    public void rejectRecharge(int userId) throws Exception {
        String sql = "UPDATE users SET balance_status = 'rejected' WHERE user_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new UserDaoException("审核拒绝用户充值失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    // 更新用户的充值请求状态
    @Override
    public boolean updateRechargeRequest(User user) throws Exception {
        String sql = "UPDATE users SET balance_status = 'pending', amount_to_be_recharged = ? WHERE user_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, user.getAmountToBeRecharged());
            pstmt.setInt(2, user.getUserid());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new UserDaoException("更新用户的充值请求状态失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    // 查询用户的充值状态
    @Override
    public String getRechargeStatus(int userId) throws Exception {
        String sql = "SELECT balance_status FROM users WHERE user_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getString("balance_status");
            }
        } catch (SQLException e) {
            throw new UserDaoException("查询用户的充值状态失败：" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
        return "unknown";
    }

    // 更新用户余额
    @Override
    public boolean updateUserBalance(int userId, double newBalance) throws Exception {
        String sql = "UPDATE users SET balance = ? WHERE user_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1, newBalance);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            throw new UserDaoException("更新用户余额失败" + e.getMessage(), e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }
}
